<?php


namespace App\Http\Controllers\Admin\Channel;

use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use App\Services\Tools\ExportService;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BaseController;

class PlatformDataController extends BaseController
{
    /**
     * @api {get} /statistics/platform/summary 平台汇总数据（平台事件统计）
     *
     * @apiGroup 平台用户事件
     *
     * @apiParam {int} date_tag 日期标签：-1：昨日；1(默认)：今日；3：近3天；7：近7天；0：自定义日期范围
     * @apiParam {string} sd_start_date 开始日期，yyyy-mm-dd，当date_tag=0时必传
     * @apiParam {string} sd_end_date 开始日期，yyyy-mm-dd，当date_tag=0时必传
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data":{
        "day_active": "11", 日活
        "recharge_user_num": "0", 充值人数
        "recharge_count": "0", 充值次数
        "recharge_amount": "0.00", 充值金额
        "lottery_amount": "0", 抽奖金额
        "give_gift_amount": "616377588", 打赏金额
        "watch_live_duration": "273.8", 观看直播时长
        "next_day_online_num": "0", 次日留存用户数
        "third_day_online_num": "0", 第三日留存用户数
        "seventh_day_online_num": "0", 第七日留存用户数
        "fifteenth_day_online_num": "0", 第十五日留存用户数
        "thirtieth_day_online_num": "0" 第三十日留存用户数
        }
    }
     */
    public function summary(Request $request)
    {
        $param = $request->only('date_tag', 'sd_start_date', 'sd_end_date');
        $v = app('validator')->make($param, [
            'date_tag' => 'integer|in:-1,1,3,7,0',
            'sd_start_date' => 'required_if:date_tag,0|date_format:Y-m-d',
            'sd_end_date' => 'required_if:date_tag,0|date_format:Y-m-d',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $data = app('repo_statistics')->getPlatformSummaryData($param);
        return Response::sendData($data);
    }

    /**
     * @api {get} /statistics/platform/day-summary 平台每日汇总列表（事件统计）
     *
     * @apiGroup 平台用户事件
     *
     * @apiParam {string} start_date 开始日期，yyyy-mm-dd
     * @apiParam {string} end_date 开始日期，yyyy-mm-dd
     * @apiParam {int} new_old_user 新老用户，-1(默认)：不限制；1：新用户；2：老用户
     * @apiParam {int} channel_id 渠道id，-1(默认)：不限制；0：非渠道；其它根据接口
     * @apiParam {int} channel_stage_id 渠道分期id，-1(默认)：不限制；其它根据接口
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "date": "2021-10-11", 日期，其它参数含义同平台事件统计接口
    "day_active": "11",
    "recharge_user_num": "0",
    "recharge_count": "0",
    "recharge_amount": "0.00",
    "lottery_amount": "0",
    "give_gift_amount": "616377588",
    "watch_live_duration": "273.8",
    "next_day_online_num": "0",
    "third_day_online_num": "0",
    "seventh_day_online_num": "0",
    "fifteenth_day_online_num": "0",
    "thirtieth_day_online_num": "0"
    }
    ],
    "first_page_url": "http://channel/statistics/platform/everyday/data?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://channel/statistics/platform/everyday/data?page=1",
    "next_page_url": null,
    "path": "http://channel/statistics/platform/everyday/data",
    "per_page": 10,
    "prev_page_url": null,
    "to": 2,
    "total": 2
    }
    }
     */
    public function daySummaryList(Request $request)
    {
        $param = $request->only('start_date', 'end_date', 'new_old_user', 'channel_id', 'channel_stage_id', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'start_date' => 'date_format:Y-m-d',
            'end_date' => 'date_format:Y-m-d',
            'new_old_user' => 'integer|in:-1,1,2',
            'channel_id' => 'integer',
            'channel_stage_id' => 'integer',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $data = app('repo_statistics')->getPlatformDayData($param);
        return Response::sendData($data);
    }

    /**
     * @api {get} /statistics/platform/day-summary/export 平台每日汇总导出
     *
     * @apiGroup 平台用户事件
     *
     * @apiParam {string} start_date 开始日期，yyyy-mm-dd
     * @apiParam {string} end_date 开始日期，yyyy-mm-dd
     * @apiParam {int} new_old_user 新老用户，-1(默认)：不限制；1：新用户；2：老用户
     * @apiParam {int} channel_id 渠道id，-1(默认)：不限制；0：非渠道；其它根据接口
     * @apiParam {int} channel_stage_id 渠道分期id，-1(默认)：不限制；其它根据接口
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "download_url": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/channel/data_excel/渠道分期用户列表20211012201856.xlsx"
    }
    }
     */
    public function daySummaryExport(Request $request)
    {
        $param = $request->only('start_date', 'end_date', 'new_old_user', 'channel_id', 'channel_stage_id');
        $v = app('validator')->make($param, [
            'start_date' => 'date_format:Y-m-d',
            'end_date' => 'date_format:Y-m-d',
            'new_old_user' => 'integer|in:-1,1,2',
            'channel_id' => 'integer',
            'channel_stage_id' => 'integer',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $data = app('repo_statistics')->getPlatformDayData($param, 0);

        $headings = [
            '日期',
            '日活',
            '充值人数',
            '充值次数',
            '充值金额',
            '抽奖金额',
            '打赏金额',
            '观看直播时长',
            '次日留存',
            '第三日留存',
            '第七日留存',
            '第十五日留存',
            '第三十日留存',
        ];

        $filename = '/channel/data_excel/' . 'daily_summary_data' . date('YmdHis') . '.xlsx';
        $res = app('excel')->store(new ExportService($data, $headings), $filename, 'oss', 'Xlsx');
        if (!$res) throw new BasicException(0, '导出失败');

        return Response::sendData([
            "download_url" => 'https://'.env('OSS_BUCKET').'.'.env('OSS_ENDPOINT').$filename,
        ]);
    }

    /**
     * @api {get} /statistics/platform/day-detail 平台每日详情列表
     *
     * @apiGroup 平台用户事件
     *
     * @apiParam {string} date 日期，必须
     * @apiParam {id} channel_id 渠道id，-1：不限制；其它根据接口
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 33,
    "date": "2021-10-12",
    "channel_id": 2,
    "channel_stage_id": 1,
    "is_new_user": 1,
    "day_active": 0,
    "recharge_user_num": 0,
    "recharge_count": 0,
    "recharge_amount": "0.00",
    "lottery_amount": 0,
    "give_gift_amount": 0,
    "watch_live_duration": "0.0",
    "next_day_online_num": 0,
    "third_day_online_num": 0,
    "seventh_day_online_num": 0,
    "fifteenth_day_online_num": 0,
    "thirtieth_day_online_num": 0,
    "channel_name": "头条"
    "channel_stage_name": "分期1"
    }
    ],
    "first_page_url": "http://channel/statistics/platform/day-detail?page=1",
    "from": 1,
    "last_page": 4,
    "last_page_url": "http://channel/statistics/platform/day-detail?page=4",
    "next_page_url": "http://channel/statistics/platform/day-detail?page=2",
    "path": "http://channel/statistics/platform/day-detail",
    "per_page": 10,
    "prev_page_url": null,
    "to": 10,
    "total": 32
    }
    }
     */
    public function dayDetailList(Request $request)
    {
        $param = $request->only('date', 'channel_id', 'page', 'page_size');
        $v = app('validator')->make($param, [
            'date' => 'required|date_format:Y-m-d',
            'channel_id' => 'integer',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $date = $param['date'];
        $channelId = $param['channel_id'] ?? -1;
        $pageSize = $param['page_size'] ?? 10;

        $list = app('model_platform_everyday_data')
            ->select('date', 'channel_id', 'channel_stage_id', 'is_new_user', 'day_active', 'recharge_user_num', 'recharge_count', 'recharge_amount', 'lottery_amount', 'give_gift_amount', 'watch_live_duration', 'next_day_online_num', 'third_day_online_num', 'seventh_day_online_num', 'fifteenth_day_online_num', 'thirtieth_day_online_num')
            ->where('date', $date)
            ->where(function ($query) use ($channelId) {
                if ($channelId != -1) {
                    $query->where('channel_id', $channelId);
                }
            })
            ->paginate($pageSize);

        //查询所有渠道
        $channelIdNameMap = app('model_channel')->getChannelIdNameMap();
        //查询所有分期
        $channelStageIdNameMap = app('model_channel_stage')->getChannelStageIdNameMap();

        foreach ($list as &$v) {
            $v['channel_name'] = $channelIdNameMap[$v['channel_id']] ?? '非渠道';
            $v['channel_stage_name'] = $channelStageIdNameMap[$v['channel_stage_id']] ?? '非分期';
        }
        return Response::sendData($list);
    }

    /**
     * @api {get} /statistics/platform/day-detail/export 平台每日详情导出
     *
     * @apiGroup 平台用户事件
     *
     * @apiParam {string} export_start_date 开始日期，必须
     * @apiParam {string} export_end_date 结束日期，必须
     * @apiParam {string} channel_ids 渠道id，-1：不限制，其它根据接口，多个之间用英文逗号连接
     * @apiParam {int} new_old_user 新老用户，-1：不限制；1：新用户；2：老用户
     *
     * @apiSuccessExample 成功响应
     * {
    "code": 200,
    "data": {
    "download_url": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/channel/data_excel/平台日详情20211013111229.xlsx"
    }
    }
     */
    public function dayDetailExport(Request $request)
    {
        $param = $request->only('export_start_date', 'export_end_date', 'channel_ids', 'new_old_user');
        $v = app('validator')->make($param, [
            'export_start_date' => 'required|date_format:Y-m-d',
            'export_end_date' => 'required|date_format:Y-m-d',
            'new_old_user' => 'integer|in:-1,1,2',
        ]);
        if ($v->fails()) throw new BasicException(0, $v->errors()->first());

        $exportStartDate = $param['export_start_date'];
        $exportEndDate = $param['export_end_date'];
        $channelIds = $param['channel_ids'] ?? -1;
        $newOldUser = $param['new_old_user'] ?? -1;

        if (strtotime($exportEndDate) - strtotime($exportStartDate) > 180 * 86400) {
            throw new BasicException(0, '日期范围不能超过180天');
        }

        $where = $whereFunc = [];
        if ($channelIds != -1) {
            $channelIds = explode(',', $channelIds);
            $whereFunc = function ($query) use ($channelIds) {
                $query->whereIn('channel_id', $channelIds);
            };
        }
        if ($newOldUser == 1) {
            $where[] = ['is_new_user', '=', 1];
        } else if ($newOldUser == 2) {
            $where[] = ['is_new_user', '=', 0];
        }
        $data = app('model_platform_everyday_data')
            ->select('date', 'channel_id', 'channel_stage_id', 'is_new_user', 'day_active', 'recharge_user_num', 'recharge_count', 'recharge_amount', 'lottery_amount', 'give_gift_amount', 'watch_live_duration', 'next_day_online_num', 'third_day_online_num', 'seventh_day_online_num', 'fifteenth_day_online_num', 'thirtieth_day_online_num')
            ->whereBetween('date', [$exportStartDate, $exportEndDate])
            ->where($where)
            ->where($whereFunc)
            ->orderBy('date')
            ->orderBy('channel_id')
            ->get()->toArray();

        //查询所有渠道
        $channelIdNameMap = app('model_channel')->getChannelIdNameMap();
        //查询所有分期
        $channelStageIdNameMap = app('model_channel_stage')->getChannelStageIdNameMap();

        foreach ($data as &$v) {
            $v['channel_id'] = $channelIdNameMap[$v['channel_id']] ?? '非渠道';
            $v['channel_stage_id'] = $channelStageIdNameMap[$v['channel_stage_id']] ?? '非分期';
            $v['is_new_user'] = $v['is_new_user'] == 1 ? '新用户' : '老用户';
            foreach ($v as &$v2) {
                $v2 = (string)$v2;
            }
        }

        $headings = [
            '日期',
            '所属渠道',
            '所属分期',
            '新老用户',
            '日活',
            '充值人数',
            '充值次数',
            '充值金额',
            '抽奖金额',
            '打赏金额',
            '观看直播时长',
            '次日留存',
            '第三日留存',
            '第七日留存',
            '第十五日留存',
            '第三十日留存',
        ];

        $filename = '/channel/data_excel/' . 'daily_data' . date('YmdHis') . '.xlsx';
        $res = app('excel')->store(new ExportService($data, $headings), $filename, 'oss', 'Xlsx');
        if (!$res) throw new BasicException(0, '导出失败');

        return Response::sendData([
            "download_url" => 'https://'.env('OSS_BUCKET').'.'.env('OSS_ENDPOINT').$filename,
        ]);
    }
}